package com.jacobson.huobi.utils

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Build
import android.text.format.DateFormat
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import com.jacobson.huobi.R
import com.jacobson.huobi.common.constants.AlarmTypeConstant
import com.jacobson.huobi.common.constants.LinkStatusConstant
import com.jacobson.huobi.entities.AlarmInfo
import com.jacobson.huobi.entities.SymbolInfo
import com.jacobson.huobi.mvp.MainActivity
import java.util.*
import java.util.concurrent.atomic.AtomicInteger


object NotificationHelper {
    @RequiresApi(api = Build.VERSION_CODES.O)
    private lateinit var keepLiveChannel: NotificationChannel
    @RequiresApi(api = Build.VERSION_CODES.O)
    private lateinit var alarmChannel: NotificationChannel
    private val counter = AtomicInteger(1)

    fun init(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            initForVersionO(context)
        }
    }

    fun sendAlarmNotification(
        context: Context,
        symbolInfoList: ArrayList<SymbolInfo>?
    ) {
        val number = symbolInfoList?.size ?: 0
        val intent = Intent(context, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
        val channelId = ResourcesUtil.formatString(R.string.channel_id_alarm)
        val channelTicker = ResourcesUtil.formatString(R.string.channel_ticker_alarm, number)
        val channelTitle = ResourcesUtil.formatString(R.string.app_name)
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 26以上，需要创建Channel
            manager.createNotificationChannel(alarmChannel)
        }

        symbolInfoList?.forEachIndexed {
                index, symbolInfo ->
            var alarmSetting = SettingProperties.getAlramSetting()
            val data = ArrayList<AlarmInfo>()
            if(alarmSetting.equals("1H报警")){
                if(symbolInfo.alarmH1.status==2 && LinkStatusConstant.getAlarmH1Code(symbolInfo.alarmH1.extraSign)) {
                    data.add(symbolInfo.alarmH1)
                }
            }else if(alarmSetting.equals("4H报警")){
                if(symbolInfo.alarmH1.status==2 && LinkStatusConstant.getAlarmH4Code(symbolInfo.alarmH1.extraSign)){
                    data.add(symbolInfo.alarmH1)
                }
                if(symbolInfo.alarmH4.status==2 && LinkStatusConstant.getAlarmH4Code(symbolInfo.alarmH4.extraSign)){
                    data.add(symbolInfo.alarmH4)
                }
            }else if(alarmSetting.equals("12H报警")){
                if(symbolInfo.alarmH1.status==2 && LinkStatusConstant.getAlarmH12Code(symbolInfo.alarmH1.extraSign)){
                    data.add(symbolInfo.alarmH1)
                }
                if(symbolInfo.alarmH4.status==2 && LinkStatusConstant.getAlarmH12Code(symbolInfo.alarmH4.extraSign)){
                    data.add(symbolInfo.alarmH4)
                }
                if(symbolInfo.alarmH12.status==2 && LinkStatusConstant.getAlarmH12Code(symbolInfo.alarmH12.extraSign)){
                    data.add(symbolInfo.alarmH12)
                }
            }else if(alarmSetting.equals("一天报警")){
                if(symbolInfo.alarmH1.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmH1.extraSign)){
                    data.add(symbolInfo.alarmH1)
                }
                if(symbolInfo.alarmH4.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmH4.extraSign)){
                    data.add(symbolInfo.alarmH4)
                }
                if(symbolInfo.alarmH12.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmH12.extraSign)){
                    data.add(symbolInfo.alarmH12)
                }
                if(symbolInfo.alarmDay.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmDay.extraSign)){
                    data.add(symbolInfo.alarmDay)
                }
            }else if(alarmSetting.equals("全部")){
                if(symbolInfo.alarmH1.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmH1.extraSign)){
                    data.add(symbolInfo.alarmH1)
                }
                if(symbolInfo.alarmH4.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmH4.extraSign)){
                    data.add(symbolInfo.alarmH4)
                }
                if(symbolInfo.alarmH12.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmH12.extraSign)){
                    data.add(symbolInfo.alarmH12)
                }
                if(symbolInfo.alarmDay.status==2 && LinkStatusConstant.getAlarmDayCode(symbolInfo.alarmDay.extraSign)){
                    data.add(symbolInfo.alarmDay)
                }
            }
            data?.forEachIndexed {
                    index, alarmdata ->
                val channelName = ResourcesUtil.formatString(
                    R.string.notification_alarm_format,
                    DateFormat.format("dd-HH:mm", alarmdata.dateTime * 1000).toString(),
                    symbolInfo.currency + symbolInfo.transCurrency,
                    AlarmTypeConstant.getDescByValue(alarmdata.type),
                    symbolInfo.realPrice
                )
                val notification = NotificationCompat.Builder(context, channelId)
                    // 设置标题，必要
                    .setContentTitle(channelTitle)
                    // 设置内容，必要
                    .setContentText(channelName)
                    // 设置时间，默认设置，可以忽略
                    .setWhen(System.currentTimeMillis())
                    // 设置通知栏的小图标，必须设置, 此处大小图片一致
                    .setSmallIcon(R.mipmap.ic_launcher)
                    // 设置通知栏大图标
                    .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
                    // 设置自动删除，点击通知栏信息之后系统会自动将状态栏的通知删除，要与setContentIntent连用
                    .setAutoCancel(true)
                    // 设置在通知栏中点击该信息之后的跳转，参数是一个pendingIntent
                    .setContentIntent(pendingIntent)
                    // 通知在第一次到达时在状态栏中显示的文本
                    .setTicker(channelTicker)
                    .setGroup("alarm")
                    .setGroupSummary(index == 0)
                    // 默认闪灯和震动
                    .setDefaults(Notification.DEFAULT_LIGHTS or Notification.DEFAULT_VIBRATE)
                    // 构建通知
                    .build()
                manager.notify(counter.getAndIncrement(), notification)

            }

        }
    }

    fun createForegroundNotification(context: Context): Notification {
        val intent = Intent(context, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(context, 0, intent, 0)
        val manger = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val channelId = ResourcesUtil.formatString(R.string.channel_id_keep_live)
        val channelName = ResourcesUtil.formatString(R.string.channel_name_keep_live)
        val channelTitle = ResourcesUtil.formatString(R.string.app_name)
        val ticker = ResourcesUtil.formatString(R.string.channel_ticker_keep_live)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 26以上，需要创建Channel
            manger.createNotificationChannel(keepLiveChannel)
        }
        return NotificationCompat.Builder(context, channelId)
            // 设置标题，必要
            .setContentTitle(channelTitle)
            // 设置内容，必要
            .setContentText(channelName)
            // 设置时间，默认设置，可以忽略
            .setWhen(System.currentTimeMillis())
            // 设置通知栏的小图标，必须设置,
            .setSmallIcon(R.mipmap.ic_launcher)
            // 设置通知栏大图标
            .setLargeIcon(BitmapFactory.decodeResource(context.resources, R.mipmap.ic_launcher))
            // 设置自动删除，点击通知栏信息之后系统会自动将状态栏的通知删除，要与setContentIntent连用
            .setAutoCancel(true)
            // 设置在通知栏中点击该信息之后的跳转，参数是一个pendingIntent
            .setContentIntent(pendingIntent)
            // 设置滑动消失的跳转，参数是一个pendingIntent
//            .setDeleteIntent(pendingIntent)
            // 设置成true，左右滑动的时候就不会被删除了，如果想删除可以在之。
            .setOngoing(true)
            // 通知在第一次到达时在状态栏中显示的文本
            .setTicker(ticker)
            // 分组
            .setGroup("Foreground")
            .setGroupSummary(true)
            // 默认闪灯和震动
            .setDefaults(Notification.DEFAULT_LIGHTS or Notification.DEFAULT_VIBRATE)
            // 构建通知
            .build()
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initForVersionO(context: Context) {
        initKeepAliveChannel(context)
        initAlarmChannel(context)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initAlarmChannel(context: Context) {
        val channelId = ResourcesUtil.formatString(context, R.string.channel_id_alarm)
        val channelName = ResourcesUtil.formatString(context, R.string.channel_name_alarm)
        alarmChannel = NotificationChannel(
            channelId,
            channelName,
            NotificationManager.IMPORTANCE_DEFAULT
        )
        alarmChannel.description =
            ResourcesUtil.formatString(context, R.string.channel_description_alarm)
        // 不需要通知声音
        alarmChannel.setSound(null, null)
        alarmChannel.enableLights(true)
        alarmChannel.lightColor = Color.RED
        alarmChannel.enableVibration(true)
        alarmChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
    }

    @RequiresApi(Build.VERSION_CODES.O)
    private fun initKeepAliveChannel(context: Context) {
        val channelId = ResourcesUtil.formatString(context, R.string.channel_id_keep_live)
        val channelName = ResourcesUtil.formatString(context, R.string.channel_name_keep_live)
        keepLiveChannel = NotificationChannel(
            channelId,
            channelName,
            NotificationManager.IMPORTANCE_HIGH
        )
        keepLiveChannel.description =
            ResourcesUtil.formatString(context, R.string.channel_description_keep_live)
        keepLiveChannel.setSound(null, null)
        keepLiveChannel.enableLights(true)
        keepLiveChannel.lightColor = Color.RED
//        keepLiveChannel.enableVibration(true)
//        keepLiveChannel.vibrationPattern = longArrayOf(100, 200, 300, 400, 500, 400, 300, 200, 400)
    }

}